import axios from 'axios';
import { host } from './env';
import { message } from 'antd';
import store from '../store';

axios.defaults.baseURL = host;
axios.defaults.withCredentials = false;

axios.interceptors.request.use(
	config => {
		if(store.userStore.token) {
			config.headers['vf'] =  store.userStore.token;
		}
		return config;
	},
	err => {
		Promise.reject(err);
	});

axios.interceptors.response.use(
	response => {
		return Promise.resolve(response.data);
	},
	err => {
		const response = err.response;
		if(!response) {
			message.error('Network error.'); 
		}else {
			switch (response.status) {
			case 400:
			case 401:
				store.userStore.history.replace('/login');
				message.error('未授权，请重新认证.');
				break;
			case 403:
				message.error('没有权限, 请联系管理员.');
				break;
			case 500:
				message.error('服务器出现异常.');
				break;
			default:
				message.error('Uncatch error.');
			}
		}
	});

export default axios;